<!--
 * @Author: chunlai
 * @Date: 2025-07-15 09:00:21
 * @LastEditTime: 2025-09-11 09:06:36
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\views\index\feecount\BbrFactors.vue
 * @Description: 被保人试算因子
-->
<template>
  <div class="bbr-factor-form" :class="pindex > 0 ? 'mt6' : ''">
    <div class="topSec thin-border" v-if="bbrListNum > 1">
      <div class="flex_ac ft14" style="line-height: 20px">
        被保人{{ `${pindex + 1}` }}
        <span
          :class="enfold ? 'ms-row2-icon' : 'ms-row-icon'"
          style="margin-left: 8px"
          @click="enfold = !enfold"
        ></span>
      </div>
      <div class="flex_ac">
        <MsImgIcon name="delete" class="ml20" @click.native="delUserItem" />
      </div>
    </div>
    <van-field
      label-width="100px"
      :input-align="inputAlign"
      class="refname"
      v-model="userInfo.name"
      clearable
      placeholder="请输入"
      @focus="tipsInfo.name = ''"
      :error="tipsInfo.name !== ''"
      :error-message="tipsInfo.name"
      v-if="formApiReg.hasOwnProperty('name')"
    >
      <div slot="label" class="flex_ac">
        <span class="mr5">姓名</span>
        <div
          class="same_to_btn"
          :class="sameWithAppnt ? 'is_same_res' : ''"
          @click.stop="
            tipsInfo.name = '';
            sameToAppnt($event, 'name');
          "
        >
          同投保人
        </div>
      </div>
    </van-field>
    <div class="enfold-line" :key="`bbr${pindex}mode3`" v-show="enfold">
      <div :key="`bbr${pindex}mode4`" v-show="!sameWithAppnt">
        <van-field
          label="证件类型"
          :input-align="inputAlign"
          class="refidType"
          @click="
            showPopAction('picker', 'idType', idTypeList, userInfo.idType)
          "
          @focus="tipsInfo.idType = ''"
          :value="userInfo.idName"
          readonly
          placeholder="请选择"
          :error="tipsInfo.idType !== ''"
          :error-message="tipsInfo.idType"
          v-if="formApiReg.hasOwnProperty('idType')"
        >
          <span
            class="ms-row-icon"
            slot="right-icon"
            v-if="idTypeList.length > 1"
          ></span>
        </van-field>
        <van-field
          class="refidNum"
          label="证件号码"
          :input-align="inputAlign"
          v-model="userInfo.idNum"
          clearable
          placeholder="请输入"
          @click="tipsInfo.idNum = ''"
          @focus="foI = true"
          @blur="
            foI = false;
            changeIdNum();
          "
          :error="tipsInfo.idNum !== ''"
          :error-message="tipsInfo.idNum"
        >
        </van-field>
        <van-field label="性别" :input-align="inputAlign" class="refsex">
          <div slot="input">
            <span class="btn_text thin-border" v-if="disabled2Sex">
              {{ userInfo.sex == "1" ? "女" : "男" }}
            </span>
            <MsRadios
              v-else
              :curVal="userInfo.sex"
              :arrList="sexList"
              type="sex"
              @change="changeMsRadio"
            />
          </div>
        </van-field>
        <van-field
          label="出生日期"
          placeholder="请选择"
          :input-align="inputAlign"
          class="refbirthDate"
          @click-input="showPopAction('date', 'birthDate', [])"
          :error="tipsInfo.birthDate !== ''"
          :error-message="tipsInfo.birthDate"
          readonly
        >
          <div class="age-box" slot="input">
            <span v-if="userInfo.birthDate"
              >{{ userInfo.birthDate }} ( {{ ageVal }}周岁 )
            </span>
            <span v-else style="color: #999">请选择</span>
          </div>
          <span
            class="ms-row-icon"
            slot="right-icon"
            v-if="!disabled2Sex"
          ></span>
        </van-field>
        <van-field
          label="职业名称"
          :input-align="inputAlign"
          class="border-line lr100"
          :class="`bbr${pindex}_occupationCode`"
          :value="userInfo.occupationCodeName"
          @click="
            showPopAction('job', 'occupationCode', []);
            tipsInfo.occupationCode = '';
          "
          type="textarea"
          rows="1"
          autosize
          readonly
          placeholder="请选择"
          :error="tipsInfo.occupationCode !== ''"
          :error-message="tipsInfo.occupationCode"
          v-if="formApiReg.hasOwnProperty('occupationCode')"
        >
          <span class="ms-row-icon" slot="right-icon"></span>
        </van-field>
        <van-field
          label="是否有社保"
          :input-align="inputAlign"
          class="border-line lr100"
          :class="`bbr${pindex}_socialInsuFlag`"
          readonly
          @focus="tipsInfo.socialInsuFlag = ''"
          :error="tipsInfo.socialInsuFlag !== ''"
          :error-message="tipsInfo.socialInsuFlag"
          v-if="formApiReg.hasOwnProperty('socialInsuFlag')"
        >
          <template #input>
            <MsRadios
              :curVal="userInfo.socialInsuFlag"
              :arrList="socialSecList"
              type="socialInsuFlag"
              @change="changeMsRadio"
            />
          </template>
        </van-field>
      </div>
      <van-field
        label="健康问卷"
        :key="`bbr${pindex}mode2`"
        :class="`bbr${pindex}_healthyStatus`"
        :input-align="inputAlign"
        readonly
        @click="tipsInfo.healthyStatus = ''"
        :error="tipsInfo.healthyStatus !== ''"
        v-if="formApiReg.hasOwnProperty('healthyStatus') && noticeMode == '1'"
      >
        <div class="age-box" slot="input" @click="openHealthPop">
          <span v-if="userInfo.healthyStatus !== ''">
            {{ userInfo.healthyStatus == "1" ? "通过" : "不通过" }}
          </span>
          <span v-else style="color: #c0c4cc">请确认健康状况</span>
        </div>
        <span class="ms-row-icon" slot="right-icon"></span>
      </van-field>
    </div>
    <!-- 下拉选择 -->
    <van-popup v-model="showPop" round position="bottom">
      <van-picker
        v-if="popConfig.type == 'picker'"
        ref="picker"
        show-toolbar
        :columns="viewOptions"
        @confirm="onConfirmPick"
        @cancel="showPop = false"
        :default-index="defaultIndex"
      >
        <div slot="title" class="keyBox" v-if="popConfig.list.length > 8">
          <input
            type="text"
            class="keyInput"
            placeholder="请输入关键字查询"
            v-model="keyWord"
          />
        </div>
      </van-picker>
      <van-datetime-picker
        v-else-if="popConfig.type == 'date'"
        :value="currentDate"
        :min-date="minDate"
        :max-date="maxDate"
        type="date"
        @confirm="confirmBirthDate"
        @cancel="showPop = false"
      />
      <OccupationPop
        v-else-if="popConfig.type == 'job'"
        utype="tbr"
        @cancel="showPop = false"
        @confirm="confirmJob"
      />
    </van-popup>
    <HealthyNotice ref="healthyRef" @sureClick="sureClick" v-if="noticePop" />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import HealthyNotice from "./HealthyNotice";
import { popupMixin } from "@/mixins/popup";
import { validateSimpleInfo } from "./validate";
import { feeCountMixin } from "./count";
import { userAge } from "@/methods/globals";
import { dateToString } from "@/methods/date.js";
export default {
  name: "BbrFactors",
  props: {
    pindex: {
      type: Number,
      default: () => 0,
    },
  },
  components: { HealthyNotice },
  data() {
    return {
      userType: "被保险人",
      userFlag: `bbr${this.pindex + 1}`,
      userInfo: {
        relationToAppnt: "",
        relationToAppntName: "",
        healthyStatus: "",
      },
      enfold: true,
      noticePop: false,
    };
  },
  computed: {
    ...mapGetters({
      appnt: "insert/appnt",
      idTypeList: "dictionary/insuredIdTypeList",
      formApiReg: "infoReg/bbrApiReg",
      tbBirthStrMin: "infoReg/bbBirthMin",
      tbBirthStrMax: "infoReg/bbBirthMax",
      noticeMode: "page/noticeMode",
      countFeeMode: "page/countFeeMode",
    }),
    bbrListNum() {
      return this.bbrMultList.length;
    },
    sameWithAppnt() {
      let res = false;
      if (this.appnt.idNum && this.userInfo.idNum == this.appnt.idNum) {
        res = true;
        this.changeData(
          {
            relationToAppnt: "4",
            relationToAppntName: "本人",
          },
          "0"
        );
      } else {
        this.changeData(
          {
            relationToAppnt: "",
            relationToAppntName: "",
          },
          "0"
        );
      }
      return res;
    },
  },
  watch: {
    userInfo: {
      handler: function (val) {
        if (this.pageLoad) {
          this.$store.commit("insert/UPDATE_MULT_BBR", {
            index: this.pindex,
            data: val,
          });
        }
      },
      deep: true,
    },
    "applicant.name": {
      handler: function (val) {
        if (this.pageLoad) {
          if (this.sameWithAppnt && val) {
            this.userInfo.name = val;
          }
        }
      },
      deep: true,
    },
  },
  mixins: [popupMixin, feeCountMixin],
  created() {
    const bbtItem = this.bbrMultList[this.pindex];
    Object.keys(this.userInfo).map((key) => {
      if (bbtItem.hasOwnProperty(key)) {
        this.userInfo[key] = bbtItem[key];
      }
    });
    this.initPreDefData();
    this.$nextTick(() => {
      this.pageLoad = true;
    });
  },
  mounted() {},
  methods: {
    async saveForm() {
      let label = "被保人";
      if (this.bbrMultList.length > 1) {
        label = `被保人${this.pindex + 1}`;
      }
      // 校验+提交
      let bbrItem = JSON.parse(JSON.stringify(this.userInfo));
      if (bbrItem.relationToAppnt == "4") {
        const tbrInfo = JSON.parse(JSON.stringify(this.appnt));
        Object.keys(tbrInfo).map((key) => {
          if (bbrItem.hasOwnProperty(key)) {
            bbrItem[key] = tbrInfo[key];
          }
        });
        bbrItem.relationToAppnt = "4";
        bbrItem.relationToAppntName = "本人";
        this.$store.commit("insert/UPDATE_MULT_BBR", {
          index: this.pindex,
          data: bbrItem,
        });
      }
      // return console.log('被保人校验');
      const iptCfg = JSON.parse(JSON.stringify(this.formApiReg));
      let res = await validateSimpleInfo(iptCfg, bbrItem, label);
      if (res.status == false) {
        this.tipsInfo[res.target] = res.msg;
        this.$store.commit("common/SET_FIELD_MEAN_CONT", {
          label: `规则校验`,
          desc: `${label}：${res.msg}`,
        });
      }
      return res;
    },
    sameToAppnt(event, type) {
      if (event) event.preventDefault();
      if (!this.applicant.idNum) {
        return this.$store.commit("common/SET_FIELD_MEAN_CONT", {
          label: `规则校验`,
          desc: `请填写投保人信息`,
        });
      }
      let err = "";
      const bbrSelf = this.bbrMultList.find(
        (e) => e.idNum == this.applicant.idNum
      );
      if (bbrSelf && !this.sameWithAppnt) {
        err = "被保人不可有多个同投保人";
      }
      if (err) {
        this.tipsInfo[type] = err;
        return;
      }
      this.sameWithAppnt ? this.toSameTbr("0") : this.toSameTbr("1");
    },
    toSameTbr(keyId) {
      const demo = JSON.parse(JSON.stringify(this.formApiReg));
      const data = JSON.parse(JSON.stringify(this.userInfo));
      let obj = Object.assign({}, demo);
      if (keyId == "1") {
        const tbrInfo = JSON.parse(JSON.stringify(this.appnt));
        Object.keys(tbrInfo).map((key) => {
          if (obj.hasOwnProperty(key)) {
            obj[key] = tbrInfo[key];
          }
        });
        obj.relationToAppnt = "4";
        obj.relationToAppntName = "本人";
      } else {
        obj.relationToAppnt = "";
        obj.relationToAppntName = "";
        obj.idType = "0";
        obj.sex = "1";
        const birthStr = dateToString(this.tbBirthStrMax);
        obj.age = userAge(birthStr);
        obj.birthDate = birthStr;
        obj.socialInsuFlag = "Y";
      }
      obj.risks = data.risks || [];
      // console.log(obj);
      this.changeData(obj);
    },
    delUserItem() {
      this.$baseConfirm("是否要删除该被保人?", () => {
        this.$store.dispatch("insert/delBbrItem", this.pindex);
        this.$store.commit("updateLoad", true);
        this.$store.commit("common/SET_BBR_REFRESH", false);
        setTimeout(() => {
          this.$store.commit("common/SET_BBR_REFRESH", true);
          this.$store.commit("updateLoad", false);
          this.changeData({});
        }, 30);
      });
    },
    openHealthPop() {
      this.noticePop = true;
      let label = "被保险人";
      if (this.bbrMultList.length > 1) {
        label = `被保险人${this.pindex + 1}`;
      }
      if (!this.userInfo.idNum || !this.userInfo.birthDate) {
        return this.$toast(`请填写${label}信息`);
      }
      this.$nextTick(() => {
        const data = JSON.parse(JSON.stringify(this.userInfo));
        this.$refs.healthyRef.initModal(`${label}`, data);
      });
    },
    sureClick(value) {
      this.changeData({ healthyStatus: value });
      this.noticePop = false;
    },
  },
};
</script>
<style lang="less" scoped>
.topSec {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 6px;
  &.thin-border {
    &::after {
      border: none;
      border-bottom: 1px dashed #e5e5e5;
    }
  }
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -3px;
    bottom: 0;
    margin: auto;
    width: 5px;
    height: 5px;
    border-radius: 100%;
    background-color: #ff5f4e;
  }
}
</style>
